package com.hqyj.ssm_project.controller;

import com.hqyj.ssm_project.exception.ControllerException;
import com.hqyj.ssm_project.exception.ServiceException;
import com.hqyj.ssm_project.pojo.Detp;
import com.hqyj.ssm_project.pojo.Role;
import com.hqyj.ssm_project.pojo.User;
import com.hqyj.ssm_project.pojo.User_Role;
import com.hqyj.ssm_project.service.DetpService;
import com.hqyj.ssm_project.service.RoleService;
import com.hqyj.ssm_project.service.UserService;
import com.hqyj.ssm_project.utils.PageUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private DetpService detpService;
    private Logger logger = LoggerFactory.getLogger(UserController.class);
    @RequestMapping(value = "/register.do", method = RequestMethod.GET)
     public ModelAndView register(@Validated User user, BindingResult bindingResult, ModelAndView modelAndView) throws ControllerException, ServiceException {
         logger.debug("UserController>>register start...");
         try {
             if (bindingResult.hasErrors()) {
                 FieldError usernameField = bindingResult.getFieldError("username");
                 if (usernameField != null) {
                     modelAndView.addObject("usernameField", usernameField.getDefaultMessage());
                 }
                 FieldError passwordField = bindingResult.getFieldError("password");
                 if (usernameField != null) {
                     modelAndView.addObject("passwordField", passwordField.getDefaultMessage());
                 }
                 modelAndView.setViewName("register");
             } else {
                 boolean b = userService.addUser(user);
                 if (b) {
                     System.out.println("注册成功");
                     modelAndView.addObject("username", user.getUserName());
                     modelAndView.setViewName("success");
                 } else {
                     modelAndView.addObject("error", user.getUserName() + "注册失败");
                     modelAndView.setViewName("error");
                     System.out.println("注册失败");
                 }
             }
         } catch (ServiceException e) {
             e.printStackTrace();
             throw new ServiceException("service异常", e);
         } catch (Exception e) {
             e.printStackTrace();
             throw new ControllerException("控制层异常", e);
         }
         logger.debug("UserController>>register end...");
         return modelAndView;
     }
    @RequestMapping("/index.do")
    public String indexPage() {
        return "index";
    }
    @RequestMapping("/welcomePage.do")
    public String welcomePage() {
        return "welcomePage";
    }
    @RequestMapping("/userPage.do")
    public String userPage(Integer currentNum,Model model) throws ControllerException {
        logger.debug("UserController>>userPage start...");
        if(currentNum==null){
            currentNum=1;
        }
        PageUtil<User> userPageUtil = userService.findUserByPageNumber(currentNum);
        model.addAttribute("userlist", userPageUtil);
        logger.debug("UserController>>userPage end...");
        return "userPage";
    }
    @RequestMapping(value = "/addUserPage.do", method = RequestMethod.GET)
    public String addUserPage(Model model) {
        List<Detp> detps = detpService.selectDetp();
        model.addAttribute("detpList",detps);
        List<Role> roles = roleService.selectAllRole();
        model.addAttribute("roleList",roles);
        return "addUserPage";
    }
    @RequestMapping(value = "/addUser.do", method = RequestMethod.POST)
    public String addUser(User user) throws ServiceException {
        userService.addUser(user);
        Integer roleId = user.getRole().getRoleId();
        Integer userId = user.getUserId();
        User_Role user_role=new User_Role();
        user_role.setUserId(userId);
        user_role.setRoleId(roleId);
        logger.debug("role:"+roleId+"userid"+userId);
        roleService.setRole(user_role);
        logger.debug("添加成功");
        System.out.println(user);
        return "redirect:userPage.do";
    }
    @RequestMapping(value = "/updateUserPage.do", method = RequestMethod.GET)
    public String updateUserPage(Integer id, Model model) {
        User user = userService.selectUserAndDetp(id);
        model.addAttribute("user", user);
        logger.debug("updateUserPage:----"+user);
        logger.debug("updateUserPage:----"+user.getRole());
        logger.debug("updateUserPage:----"+user.getDetp());
        List<Detp> detps = detpService.selectDetp();
        model.addAttribute("detpList",detps);
        List<Role> roles = roleService.selectAllRole();
        model.addAttribute("roleList",roles);
        return "updateUserPage";
    }
    @RequestMapping(value = "/updateUser.do", method = RequestMethod.GET)
    public String updateUser(User user) {
        logger.debug("UserController>>updateUser start...");
        System.out.println(user);
        int i = userService.updateByPrimaryKeySelective(user);
        Integer roleId = user.getRole().getRoleId();
        Integer userId = user.getUserId();
        User_Role user_role1 = roleService.seleteUser_RoleByUserId(userId);
        if(user_role1!=null){
            roleService.deletUser_Role(userId);
        }
        User_Role user_role=new User_Role();
        user_role.setUserId(userId);
        user_role.setRoleId(roleId);
        roleService.setRole(user_role);
        if (i > 0) {
            logger.debug("修改成功");
            logger.debug("UserController>>updateUser end...");
            return "redirect:userPage.do";
        } else return "error";
    }
    @RequestMapping(value = "/deleteUser.do", method = RequestMethod.GET)
    public String deleteUser(Integer id) {
        logger.debug("UserController>>deleteUser start...");
        int i = userService.deleteByPrimaryKey(id);
        if (i > 0) {
            logger.debug("删除成功");
            logger.debug("UserController>>deleteUser end...");
            return "redirect:userPage.do";
        } else return "error";
    }
/*    @RequestMapping("/updateUserStatus.do")
    public void   updateUserStatus(Integer userId,String userStatus){
        System.out.println(userId+"---"+userStatus);
    }*/
    @RequestMapping(value="updateUserStatus.do")
    public @ResponseBody Map<String,Object> login1(HttpServletRequest  request,HttpServletResponse response) throws IOException{

        String userIdstr = request.getParameter("userId");
        int userId = Integer.parseInt(userIdstr);
        String userStatus = request.getParameter("userStatus");
        User user = new User();
        user.setUserId(userId);
        if(userStatus.equals("Y")){
            user.setUserStatus("N");
        }else {
            user.setUserStatus("Y");
        }

        userService.updateByPrimaryKeySelective(user);
        User user1 = userService.selectByPrimaryKey(userId);

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("userId",userId);
        map.put("userStatus",user1.getUserStatus());
        return map;

    }



}